#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define NUM 1024
#define SIZE 64
#define SEP " "


char usercommand[NUM];
char cwd[1024];
char enval[100][100];//测试
int count_enval=0;
int lastcode;


const char *getUsername()
{
        const char *name = getenv("USER");
            if(name) return name;
                else return "none";

}
const char *getHostname()
{
        const char *hostname = getenv("HOSTNAME");
            if(hostname) return hostname;
                else return "none";

}
const char *getCwd()
{
        const char *cwd = getenv("PWD");
           if(cwd) return cwd;
                else return "none";

}

//打印命令行提示符，获取用户命令字符串
int getUserCommand(char *command, int num)
{
    printf("[%s@%s %s]# ", getUsername(), getHostname(), getCwd());
    char *r = fgets(command, num, stdin); // 最终你还是会输入\n
    if(r == NULL) return -1;
    // "abcd\n" "\n"
    command[strlen(command) - 1] = '\0'; // 有没有可能越界？不会
    return strlen(command);
}

//分割字符串
void commandSplit(char *in,char **out)
{
    int argc=0; 
    out[argc++]=strtok(in,SEP);
    while(out[argc++]=strtok(NULL,SEP));

    //for (int i=0;out[i];i++)
    //{
    //    printf("%d:%s\n",i,out[i]);
    //}
}


int execute(char *argv[])
{

         pid_t id=fork();

         if(id<0)
         {
             return -1;
         }
         if(id==0)
         {
             execvp(argv[0],argv);
             exit(1);
         }
         else
         {
             int status=0;
             pid_t rid=waitpid(-1,&status,0);
             if(rid>0)
             {
                 lastcode=WEXITSTATUS(status);
             }
         }
         return 0;
}

void cd(const char* path )
{
    chdir(path);
    char tmp[1024];
    getcwd(tmp,sizeof(tmp));
    sprintf(cwd,"PWD=%s",tmp);
    putenv(cwd);
    
}


//内键情况
int doBuildin(char *argv[])
{
   if(strcmp(argv[0],"cd")==0)
   {
       char * path=NULL;
       if(argv[1]==NULL)
       {
           path=".";
       }
       else  path=argv[1];
       cd(path);
       return 1;
   }
   else if(strcmp(argv[0],"exprot")==0)
   {
       if(argv==NULL)return 1;
       strcpy(enval[count_enval],argv[1]);
       putenv(enval[count_enval]);
       count_enval++;
       return 1;
   }
   else if(strcmp(argv[0],"echo")==0)
   {
       char *val =argv[1]+1;
       if(strcmp(val,"?")==0)
       {
           printf("%d\n",lastcode);
           lastcode=0;
       }
       else
       {
           printf("%s\n",getenv(val));
       }
       return 1;
   }
   return 0;
}



int main()
{
    while(1)
    {
		 char *argv[SIZE];
         //1.打印命令行提示符，获取用户命令字符串
         int n=getUserCommand(usercommand,sizeof(usercommand));
         if(n<0)continue;
         //2.分割字符串
         commandSplit(usercommand,argv);
        //3. 内键情况（cd,exprot...）
         n=doBuildin(argv);
         if(n) continue;
         //4.执行对应的命令
         execute(argv);
    }
    return 0;
}
